using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;


namespace theRift
{
    public sealed class FPS : Microsoft.Xna.Framework.DrawableGameComponent
    {
        private float fps;
        private float updateInterval = 1.0f;
        private float timeSinceLastUpdate = 0;
        private float frameCount = 0;

        private SpriteBatch spriteBatch;
        private SpriteFont smallFont;

        public FPS(Game game)
            : this(game, false, false, game.TargetElapsedTime) { }

        public FPS(Game game, bool isFixedTimeStep, bool syncWithVertRetrace)
            : this(game, isFixedTimeStep, syncWithVertRetrace, game.TargetElapsedTime) { }

        public FPS(Game game, bool isFixedTimeStep, bool syncWithVertRetrace, 
            TimeSpan targetElapsedTime)
            : base(game)
        {
            GraphicsDeviceManager graphics = (GraphicsDeviceManager)Game.Services.GetService(typeof(
                IGraphicsDeviceManager));

            graphics.SynchronizeWithVerticalRetrace = syncWithVertRetrace;
            Game.IsFixedTimeStep = isFixedTimeStep;
            Game.TargetElapsedTime = targetElapsedTime;

            Initialize();
        }

        public override void Initialize()
        {
            spriteBatch = (SpriteBatch)Game.Services.GetService(typeof(SpriteBatch));
            smallFont = Game.Content.Load<SpriteFont>(@"Fonts/smallFont");

            base.Initialize();
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            float elapsed = (float)gameTime.ElapsedRealTime.TotalSeconds;
            frameCount++;
            timeSinceLastUpdate += elapsed;

            if (timeSinceLastUpdate > updateInterval)
            {
                fps = frameCount / timeSinceLastUpdate;        
                frameCount = 0;
                timeSinceLastUpdate -= updateInterval;
            }

            spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred,
                SaveStateMode.SaveState);
            spriteBatch.DrawString(smallFont, "FPS: " + (int)fps, Vector2.Zero, Color.Black);
            spriteBatch.End();
            
            base.Draw(gameTime);
        }
    }
}